import request from '@/utils/request'

// ==================== 接口类型定义 ====================

/**
 * 收藏项接口
 */
export interface FavoriteItem {
  favorite_id: number
  goods_id: number
  goods_info?: {
    goods_id: number
    goods_name: string
    goods_price: string
    goods_cover_img: string
    goods_status: number
  }
  create_time: string
}

/**
 * 收藏列表响应接口
 */
export interface FavoriteListResponse {
  count: number
  next: string | null
  previous: string | null
  results: FavoriteItem[]
}

/**
 * 添加收藏请求参数接口
 */
export interface AddFavoriteParams {
  goods_id: number
}

/**
 * 添加收藏响应接口
 */
export interface AddFavoriteResponse {
  favorite_id: number
  message: string
}

// ==================== API 服务 ====================

/**
 * 收藏API服务
 */
export const favoritesApi = {
  /**
   * 获取收藏列表
   * GET /auth/favorites/
   * @param params - 分页参数
   */
  getFavoritesList(params?: { page?: number; page_size?: number }): Promise<FavoriteListResponse> {
    return request({
      url: '/auth/favorites/',
      method: 'get',
      params,
    })
  },

  /**
   * 添加收藏
   * POST /auth/favorites/
   * @param params - 添加收藏参数
   */
  addToFavorites(params: AddFavoriteParams): Promise<AddFavoriteResponse> {
    return request({
      url: '/auth/favorites/',
      method: 'post',
      data: params,
    })
  },
  /**
   * 删除收藏
   * DELETE /auth/favorites/{goods_id}/
   * @param goods_id - 商品ID
   */
  removeFromFavorites(goods_id: number): Promise<any> {
    return request({
      url: `/auth/favorites/${goods_id}/`,
      method: 'delete',
    })
  },

  /**
   * 检查是否收藏
   * GET /auth/favorites/check/
   * @param params - 检查参数
   */
  checkFavoriteStatus(params: { goods_id: number }): Promise<{ is_favorited: boolean }> {
    return request({
      url: '/auth/favorites/check/',
      method: 'get',
      params,
    })
  },
}

// ==================== 工具函数 ====================

/**
 * 检查商品是否收藏
 */
export const isGoodsFavorited = async (goods_id: number): Promise<boolean> => {
  try {
    const response = await favoritesApi.checkFavoriteStatus({ goods_id })
    // 后端返回 is_favorite，前端期望 is_favorited
    return response.is_favorited || false
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return false
  }
}

/**
 * 切换收藏状态
 */
export const toggleFavorite = async (goods_id: number): Promise<boolean> => {
  try {
    const currentStatus = await isGoodsFavorited(goods_id)

    if (currentStatus) {
      // 当前已收藏，执行取消收藏
      await favoritesApi.removeFromFavorites(goods_id)
      return false
    } else {
      // 当前未收藏，执行添加收藏
      await favoritesApi.addToFavorites({ goods_id })
      return true
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    throw error
  }
}

// ==================== 默认导出 ====================

export default favoritesApi
